<?php
class ControllerSaleRequisitionMain extends Controller {
  private $error = array();

  public function vendor(){
    $this->load->model('sale/requisition');
    $json = array();
    $filter_name = I('get.filter_name');
    if(!$filter_name){
      $filter_name='';
    }
    $vendors = $this->model_sale_requisition->getVendors($filter_name);
    if($vendors){
      $json = $vendors;
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function product(){
    $json = array();

    if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
      $this->load->model('catalog/product');
      $this->load->model('catalog/option');
      $this->load->model('sale/requisition');

      

      if (isset($this->request->get['filter_name'])) {
        $filter['pd.name'] = array('like', '%'.$this->request->get['filter_name'].'%');
      }
      if(isset($this->request->get['filter_vendor'])){
        $filter['vendor.vendor'] = $this->request->get['filter_vendor'];
      }
      $results = $this->model_sale_requisition->getProducts($filter);

      foreach ($results as $result) {
        $option_data = array();

        $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

        foreach ($product_options as $product_option) {
          $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

          if ($option_info) {
            $product_option_value_data = array();

            foreach ($product_option['product_option_value'] as $product_option_value) {
              $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

              if ($option_value_info) {
                $product_option_value_data[] = array(
                  'product_option_value_id' => $product_option_value['product_option_value_id'],
                  'option_value_id'         => $product_option_value['option_value_id'],
                  'name'                    => $option_value_info['name'],
                  'price'                   => (float)$product_option_value['price'], 
                  'price_prefix'            => $product_option_value['price_prefix']
                );
              }
            }

            $option_data[] = array(
              'product_option_id'    => $product_option['product_option_id'],
              'product_option_value' => $product_option_value_data,
              'option_id'            => $product_option['option_id'],
              'name'                 => $option_info['name'],
              'type'                 => $option_info['type'],
              'value'                => $product_option['value'],
              'required'             => $product_option['required']
            );
          }
        }

        $json[] = array(
          'product_id' => $result['product_id'],
          'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
          'model'      => $result['model'],
          'cost'          => $result['product_cost'],
          'sku'         =>$result['sku'],
          'option'     => $option_data,
          'price'      => $result['price']
        );
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }
  // public function exportShipping(){
  //   $po_id = I('get.po_id');
  //   if(!$po_id){
  //     $po_id = 0;
  //   }
  //   $this->load->model('sale/requisition');
  //   $po = $this->model_sale_requisition->getPo($po_id);

  //   $data['po'] = $po;

  //   if(!$po){
  //     $this->load->language('error/not_found');
 
  //     $this->document->setTitle($this->language->get('heading_title'));

  //     $data['heading_title'] = $this->language->get('heading_title');
 
  //     $data['text_not_found'] = $this->language->get('text_not_found');
 
  //     $data['breadcrumbs'] = array();

  //     $data['breadcrumbs'][] = array(
  //       'text' => $this->language->get('heading_title'),
  //       'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
  //     );
 

  //     $data['footer'] = $this->load->controller('common/footer');
 
  //     $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
  //   }
  //   $po_products = $this->model_sale_requisition->getRequisitionProducts($po_id);
  //   $count = 0;
  //   foreach ($po_products as $key => $po_product) {
  //     $count += $po_product['qty'];
  //   }

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objReader = PHPExcel_IOFactory::createReader('Excel5');
  //   $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/order_shipping.xls"); 
  //   $objPHPExcel->getProperties()->setCreator("Think-tec")
  //              ->setLastModifiedBy("Think-tec")
  //              ->setTitle("Bai Huo Zhan PO")
  //              ->setSubject("Bai Huo Zhan PO")
  //              ->setDescription("Bai Huo Zhan PO")
  //              ->setKeywords("Bai Huo Zhan, Think-tec")
  //              ->setCategory("Think-tec");
  //   // $objPHPExcel->setActiveSheetIndex(0);
  //   $objActSheet = $objPHPExcel->getActiveSheet();
  //   $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setSize(48);
  //   $objActSheet->setCellValue('C1', $po['logcenter_info']['shipping_zone_city']);
  //   //$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  //   $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B2', $po['included_order_ids']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B3')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B3', $po['id']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B5')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B5', $po['logcenter_info']['firstname']);
  //   $objActSheet->setCellValue('B6', $po['logcenter_info']['address_1']);
  //   $objActSheet->setCellValue('B7', $po['logcenter_info']['telephone']);

  //   //$objPHPExcel->getActiveSheet()->getStyle('A7:G'.$requisitionw_num)->getFont()->setSize(12);
    
  //   $objActSheet->setTitle('调拨单');


  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');
  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output'); 
  //   exit;
  // }
  // public function export(){
  //   $po_id = I('get.po_id');
  //   if(!$po_id){
  //     $po_id = 0;
  //   }
  //   $this->load->model('sale/requisition');
  //   $po = $this->model_sale_requisition->getPo($po_id);
  //   $data['po'] = $po;
  //   if(!$po){
  //     $this->load->language('error/not_found');
 
  //     $this->document->setTitle($this->language->get('heading_title'));

  //     $data['heading_title'] = $this->language->get('heading_title');
 
  //     $data['text_not_found'] = $this->language->get('text_not_found');
 
  //     $data['breadcrumbs'] = array();

  //     $data['breadcrumbs'][] = array(
  //       'text' => $this->language->get('heading_title'),
  //       'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
  //     );
 

  //     $data['footer'] = $this->load->controller('common/footer');
 
  //     $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
  //   }
  //   $po_products = $this->model_sale_requisition->getRequisitionProducts($po_id);
  //   $data['po_products'] = $po_products;

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objReader = PHPExcel_IOFactory::createReader('Excel5');
  //   $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/po_tpl.xls"); 
  //   $objPHPExcel->getProperties()->setCreator("Think-tec")
  //              ->setLastModifiedBy("Think-tec")
  //              ->setTitle("Bai Huo Zhan PO")
  //              ->setSubject("Bai Huo Zhan PO")
  //              ->setDescription("Bai Huo Zhan PO")
  //              ->setKeywords("Bai Huo Zhan, Think-tec")
  //              ->setCategory("Think-tec");
  //   // $objPHPExcel->setActiveSheetIndex(0);
  //   $objActSheet = $objPHPExcel->getActiveSheet();
  //   $objActSheet->setCellValue('B2', $po['id']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  //   $objActSheet->setCellValue('F2', date('Y-m-d H:i',time()));
  //   $objActSheet->setCellValue('B3', $po['vendor_id']);
  //   $objActSheet->setCellValue('B4', $po['vendor']['vendor_name']);
  //   $objActSheet->setCellValue('F3', $po['vendor']['firstname']);
  //   $objActSheet->setCellValue('F4', $po['vendor']['telephone']);

  //   $requisitionw_num = 6;
  //   $styleBorderOutline = array(
  //     'borders' => array(
  //       'outline' => array(
  //         'style' => PHPExcel_Style_Border::BORDER_THIN,
  //       ),
  //     ),
  //   );
  //   $objPHPExcel->getActiveSheet()->insertNewRowBefore(7, count($po_products));
  //   $count = 0;
  //   foreach ($po_products as $key => $po_product) {
  //     $requisitionw_num++;
  //     $objActSheet->setCellValue('A'.$requisitionw_num, $requisitionw_num-6);
  //     $objActSheet->setCellValue('B'.$requisitionw_num, $po_product['name'].' '.$po_product['option_name']);
  //     $objActSheet->setCellValue('C'.$requisitionw_num, $po_product['sku']);
  //     $objActSheet->setCellValue('D'.$requisitionw_num, $po_product['qty']);
  //     $objActSheet->setCellValue('E'.$requisitionw_num, $po_product['unit_price']);
  //     $objActSheet->setCellValue('F'.$requisitionw_num, $po_product['price']);
  //     $objActSheet->setCellValue('G'.$requisitionw_num, $po_product['comment']);

  //     $count += $po_product['qty'];

  //     $objPHPExcel->getActiveSheet()->getStyle('A'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('B'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('C'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('D'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('E'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('F'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('G'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //   }
  //   $requisitionw_num++;

  //   $objActSheet->setCellValue('D'.$requisitionw_num, $count);
  //   $objActSheet->setCellValue('F'.$requisitionw_num, $po['total']);
  //   $requisitionw_num++;
  //   $objActSheet->setCellValue('F'.$requisitionw_num, date('Y-m-d', strtotime($po['deliver_time'])));

  //   $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$requisitionw_num)->getFont()->setSize(16);
    
  //   $objActSheet->setTitle('调拨单');


  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');
  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output'); 
  //   exit;
  // }

  public function index() {

    $this->document->setTitle('调拨单');

    $this->load->model('sale/requisition');

    $this->getList();
  }

  public function add() {
    $this->document->setTitle('新增调拨单');
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');
	$this->document->addScript('view/javascript/lyc_ctl.js');

    $this->load->model('sale/requisition');

    $this->form();
  }

  public function view(){

    $this->document->setTitle('查看调拨单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');
	$this->document->addScript('view/javascript/lyc_ctl.js');

    $this->load->model('sale/requisition');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '调拨单',
      'href' => $this->url->link('sale/requisition_main', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];
	$data['button_cancel'] = $this->language->get('button_cancel');
	$data['cancel'] = $this->url->link('sale/requisition_main', 'token=' . $this->session->data['token'] . $url, 'SSL');

    $id = I('get.requisition_id');
    if(!$id){
      $id=0;
    }

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
     
    $requisition = $this->model_sale_requisition->getRequisition($id);
	$req_stock = $this->model_sale_requisition->getRequisitionStock($id);
	$data['req_stock'] = $req_stock;

    $data['requisition'] = $requisition;
    $requisition_products = $this->model_sale_requisition->getRequisitionProducts($id);
    $data['requisition_products'] = $requisition_products;
    $requisition_histories = $this->model_sale_requisition->getRequisitionHistory($id);
    $data['requisition_histories'] = $requisition_histories;
    $data['included_orders'] = explode(',', $requisition['included_order_ids']);
	
	if($requisition['status']==1) {
      $data['need_logcenter_confirm'] = true;
    }

	if($requisition['status']==2) {
      $data['need_main_confirm'] = true;
    }

	if($requisition['status']==3) {
      $data['forceCompleteBtn'] = '审核完成调拨单';
    }

	if($requisition['status']==3) {
		$data['need_logcenter_accept'] = true;
    }
	
	//判断是否已经生成出入库单
	if(!$data['req_stock']) {
		$data['need_stock'] = true;
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/requisition_main_view.tpl', $data));
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/requisition');
      $data = json_decode(file_get_contents('php://input'), true);

      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      if(!$data['products']){

        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        $requisition_id = $this->model_sale_requisition->addRequisition($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$requisition_id)));
      return;
    }
  }

  public function confirmStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/requisition');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      // $id = I('post.po_id');
      $id = $data['requisition_id'];
      if(!$id){
        $id=0;
      }
      $requisition = $this->model_sale_requisition->getRequisition($id);
      //判断po状态，如果是已经结算或者已经关闭，
      if($requisition['status'] != 2 ) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改调拨单')));

      }  

        $this->model_sale_requisition->changeRequisitionStatus($id, 3);
        //确认调拨单 
        $this->event->trigger('requisition.src.addstock', $id);
        $comment = '后台确认调拨单';

        $this->model_sale_requisition->addRequisitionHistory($id, $this->user->getId(), $this->user->getUserName(), $comment);  
  

      $this->response->setOutput(json_encode(array('success'=>'后台成功确认调拨单')));
      return;
    } 
  }
	
	//生成出入库单
	public function createStock(){

		if ($this->request->server['REQUEST_METHOD'] == 'POST') {

			$this->load->model('sale/requisition');
			$data = json_decode(file_get_contents('php://input'), true);
			$filter = C('DEFAULT_FILTER');
			$data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

			$id = $data['requisition_id'];
			if(!$id){
				$id=0;
			}

			$req = $this->model_sale_requisition->getRequisition($id);
			$indata = array(
				'refer_id' => $id,
				'refer_type_id' => 4,
				'warehouse_id' => $req['in_warehouse_id'],
				'user_id' => $_SESSION['default']['user_id'],
				'buy_money' => $req['total'],
				'status' => 1
			);
			$outdata = array(
				'refer_id' => $id,
				'refer_type_id' => 4,
				'warehouse_id' => $req['out_warehouse_id'],
				'user_id' => $_SESSION['default']['user_id'],
				'sale_money' => $req['total'],
				'status' => 1
			);

			$req_products = $this->model_sale_requisition->getRequisitionProducts($id);
			foreach($req_products as $value){

				$indata['products'][] = array(
					'product_code' => $value['product_code'],
					'product_quantity' => $value['qty'],
					'product_price' => $value['unit_price'],
					'products_money' => $value['price']
				);

				$outdata['products'][] = array(
					'product_code' => $value['product_code'],
					'product_quantity' => $value['qty'],
					'product_price' => $value['unit_price'],
					'products_money' => $value['price']
				);

			}
				
			$this->load->model('stock/autodocument');
			$this->model_stock_autodocument->addStockIn($indata);
			$this->model_stock_autodocument->addStockOut($outdata);

			$comment = '提交生成出入库单';
			$message = '出入库单生成成功';	

			$this->model_sale_requisition->addRequisitionHistory($id, $this->user->getId(), $this->user->getUserName(), $comment);

			$this->response->setOutput(json_encode(array('success'=>$message)));
			return;
		}

	}

  public function delete() {
    $json = array();

    $this->load->model('sale/requisition');

    $id = I('get.requisition_id');
    if(!$id){
      $id=0;
    }

    $requisition = $this->model_sale_requisition->getRequisition($id);
    if(!$requisition||$requisition['status']!=1) {
      $json['error'] = '非新增状态调拨单不能删除';
    }
    else {
      $this->model_sale_requisition->deleteRequisition($id);
      $json['success'] = '删除成功';
    }

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  protected function form(){
        $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '调拨单',
      'href' => $this->url->link('sale/requisition_main', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];
	$data['button_cancel'] = $this->language->get('button_cancel');
	$data['cancel'] = $this->url->link('sale/requisition_main', 'token=' . $this->session->data['token'] . $url, 'SSL');

    $id = I('get.requisition_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

	/*筛选相关*/
	$this->load->model('stock/stocksearch');
	$warehouses = $this->model_stock_stocksearch->getWarehouses(); //获取全部仓库
		
	foreach ($warehouses as $value){

		$data["warehouses"][] = array(
			'warehouse_id' => $value['warehouse_id'],
			'name' => $value['name']
		);

	}
	/*筛选相关*/
    
    $requisition = $this->model_sale_requisition->getRequisition($id);
    $data['requisition'] = $requisition;
    $po_products = $this->model_sale_requisition->getRequisitionProducts($id);
    $data['requisition_products'] = $requisition_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/requisition_main.tpl', $data));
  }

  

  protected function getList() {
    $this->load->model('sale/lgi_order');
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    if($this->user->getLp()){
      $where['requisition.src_logcenter'] = $this->user->getLp();
      $where['requisition.des_logcenter'] = $this->user->getLp();
      $where['_logic'] = 'or';
      $filter['_complex'] = $where;
    }

    else if($this->user->getVp()){
      $filter['requisition.vendor_id'] = $this->user->getId();
    }
    else{
      
    }
    $data = I('get.');

    $url = '';
/*
    if(isset($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
	  $url .= '&filter_date_start=' . $filter_date_start;
    }
	else{
		$filter_date_start = '0000-00-00';
		$url .= '&filter_date_start=' . $filter_date_start;
	}

    if(isset($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end']." 23:59:59";
	  $url .= '&filter_date_end=' . $filter_date_end;
    }
	else{
		$filter_date_end = '9999-12-31 23:59:59';
		$url .= '&filter_date_end=' . $filter_date_end;
	}

    $filter['requisition.date_added'] = array('between',array($filter_date_start,$filter_date_end));
*/
    /*
     * 修正分页后时间下拉框不能操作的异常
     * @author sonicsjh
     */
    if (!empty($data['filter_date_start']) && !empty($data['filter_date_end'])) {
        $url .= '&filter_date_start='.$data['filter_date_start'].'&filter_date_end='.$data['filter_date_end'];
        $filter['requisition.date_added'] = array('between', array($data['filter_date_start'].' 00:00:00', $data['filter_date_end'].' 23:59:59'));
    }else if (!empty($data['filter_date_start'])) {
        $url .= '&filter_date_start='.$data['filter_date_start'];
        $filter['requisition.date_added'] = array('gt', $data['filter_date_start'].' 00:00:00');
    }else if (!empty($data['filter_date_end'])) {
        $url .= '&filter_date_end='.$data['filter_date_end'];
        $filter['requisition.date_added'] = array('lt', $data['filter_date_end'].' 23:59:59');
    }

	if(!empty($data['filter_out_warehouse'])){
      $filter_out_warehouse = trim($data['filter_out_warehouse']);
      $filter['requisition.out_warehouse_id'] = $filter_out_warehouse;
	  $url .= '&filter_out_warehouse=' . $filter_out_warehouse;
    }

    if(!empty($data['filter_in_warehouse'])){
      $filter_in_warehouse = trim($data['filter_in_warehouse']);
      $filter['requisition.in_warehouse_id'] = $filter_in_warehouse;
	  $url .= '&filter_in_warehouse=' . $filter_in_warehouse;
    }

    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['requisition.status'] = $filter_status;
		$url .= '&filter_status=' . $filter_status;
      }  
    }else{
      $data['filter_status'] = '*';
	  $url .= '&filter_status=' . $filter_status;
    }
    /*
     * 强制添加仓库筛选功能
     * @author sonicsjh
     */
    $data['warehouseLocked'] = false;
    if ($this->user->getLP() > 0) {
        $data['warehouseLocked'] = true;
        $filter['requisition.out_warehouse_id|requisition.in_warehouse_id'] = $this->user->getLP();
        unset($filter['requisition.in_warehouse_id']);
        unset($filter['requisition.out_warehouse_id']);
    }

	/*筛选相关*/
	$this->load->model('stock/stocksearch');
	$warehouses = $this->model_stock_stocksearch->getWarehouses(); //获取全部仓库
		
	foreach ($warehouses as $value){

		$data["warehouses"][] = array(
			'warehouse_id' => $value['warehouse_id'],
			'name' => $value['name']
		);

	}
	/*筛选相关*/

    $requisition_list =  $this->model_sale_requisition->getList($page, $filter);
    $order_total = $this->model_sale_requisition->getListCount($filter);

	foreach($requisition_list as &$value){

		if($value["status"]==1){
			$value["color"] = "blue";
		}
		else if($value["status"]==2 || $value["status"]==3){
			$value["color"] = "orange";
		}

	}

    $data['status_array'] = getRequisitionStatus();
    $data['status_array']['*'] = '全部';

	/*分页*/
	$pagination = new Pagination();
	$pagination->total = $order_total;
	$pagination->page = $page;
	$pagination->limit = $this->config->get('config_limit_admin');
	$pagination->url = $this->url->link('sale/requisition_main', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

	$data['pagination'] = $pagination->render();
	$data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($order_total - $this->config->get('config_limit_admin'))) ? $order_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $order_total, ceil($order_total / $this->config->get('config_limit_admin')));
	/*分页*/

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '调拨单',
      'href' => $this->url->link('sale/requisition_main', 'token=' . $this->session->data['token'] , 'SSL')
    );

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $data['token'] = $this->session->data['token'];
    
    $data['requisition_list'] = $requisition_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/requisition_main_list.tpl', $data));
  }

  function validateDate($date, $format = 'Y-m-d H:i:s')
  {
      $d = DateTime::createFromFormat($format, $date);
      return $d && $d->format($format) == $date;
  }

  public function genVendorBill(){
    $vendor_bill_month = I('get.year_month');
    $month_valid = $this->validateDate($vendor_bill_month, 'Y-m');
    if(!$month_valid) {
      $this->session->data['error'] = '请选择有效的年月日期';
      $this->response->redirect($this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL'));
    }
    //获取选择月份之前半年内所有还未对账的完成状态的订单
    $d = DateTime::createFromFormat('Y-m', $vendor_bill_month);
    $cur_year_month = $d->format('Y-m-01');
    $cur_month = $d->format('Y-m-21');
    $d->modify('-6 month');
    $end_month = $d->format('Y-m-d');
    $this->load->model('sale/vendor_bill');
    $this->load->model('sale/requisition');
    $billed_po = $this->model_sale_vendor_bill->getBilledPo($cur_month, $end_month);
    $billed_po_ids = array();
    foreach ($billed_po as $bo) {
      $billed_po_ids[] = $bo['po_id'];
    }

    $vendor_ids = $this->model_sale_requisition->getVendorIdsFromPo($cur_month, $end_month, $billed_po_ids);

    foreach ($vendor_ids as $vendor_id) {
      $bill_data = $this->model_sale_requisition->getToBillPo($cur_month, $end_month, $billed_po_ids, $vendor_id['vendor_id']);  
      $bill_data_full[$vendor_id['vendor_id']] = $bill_data;
    }

    $commission = 1;
    foreach ($bill_data_full as $vendor_id=>$bill_data) {
      $po_total = 0;
      $po_ids = array();
      foreach ($bill_data as $po) {
        $po_total += (float)$po['total'];
        $po_ids[] = $po['id'];
      }
      $commission_total = $po_total*$commission;
      $data = array();

      //此处的$vendor_id是po表中的vendor_id 对应的是 vendors表中的user_id
      $this->load->model('catalog/vendor');
      $vendor_info = $this->model_catalog_vendor->getVendorByUserId($vendor_id);
      $data['vendor_id'] = $vendor_info['vendor_id'];
      $data['year_month'] = $cur_year_month;
      $data['total'] = $commission_total;
      $data['po_total'] = $po_total;
      $data['date_added'] = date('Y-m-d H:i:s', time());
      $vendor_bill_id = $this->model_sale_vendor_bill->saveVendorBill($data, $po_ids);

      //添加生成po操作记录
      $this->load->model('user/user');
      $user_info = $this->model_user_user->getUser($this->user->getId());
      $comment = '新增品牌商对账单';
      $this->model_sale_vendor_bill->addVendorBillHistory($vendor_bill_id, $this->user->getId(), $user_info['fullname'], $comment);      
    }
    


    $this->session->data['success'] = '生成品牌厂商对账单成功';
    $this->response->redirect($this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'], 'SSL'));
  }

	 //仓库保存调整数量
    public function saveLgStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/requisition');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      
      if(!$data['products']){
        $this->response->setOutput(json_encode(array('error'=>'数据不完整')));
        return;
      }

      $to_save_stock = array();
      foreach ($data['products'] as $requisition_product) {
        $to_save_stock[$requisition_product['requisition_product_id']] = $requisition_product['stock'];
        $to_save_comment[$requisition_product['requisition_product_id']] = $requisition_product['comment'];
      }

      $to_save_stock2 = array();

      // $id = I('rost.ro_id');
      $id = $data['requisition_id'];
      if(!$id){
        $id=0;
      }
      $requisition = $this->model_sale_requisition->getRequisition($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量

      if($requisition['status'] != 1) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭库存调整单')));
        return;
      }

      $requisition_products = $this->model_sale_requisition->getRequisitionProducts($id);

      foreach ($requisition_products as $requisition_p) {
        if(isset($to_save_stock[$requisition_p['id']])) {
          $to_save_stock2[$requisition_p['id']] = $to_save_stock[$requisition_p['id']];
          $to_save_comment2[$requisition_p['id']] = $to_save_comment[$requisition_p['id']];
        }
        if(isset($to_save_comment[$requisition_p['id']])) {
          $to_save_comment2[$requisition_p['id']] = $to_save_comment[$requisition_p['id']];
        }
        $num_change = $requisition_p['qty']+$to_save_stock2[$requisition_p['id']];
        if($num_change<=0){
          $error_warning = "请填写正确的调整数量";
        }
      }
       if($error_warning){
        $this->response->setOutput(json_encode(array('error'=>$error_warning)));
       }else{
        $this->model_sale_requisition->setStock($id, $to_save_stock2);
        $this->model_sale_requisition->setComment($id, $to_save_comment2);
        $this->response->setOutput(json_encode(array('success'=>'修改成功')));
       }
      
      return;
    } 
  }
	
	//总后台保存调整数量
    public function saveStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/requisition');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      
      if(!$data['products']){
        $this->response->setOutput(json_encode(array('error'=>'数据不完整')));
        return;
      }

      $to_save_stock = array();
      foreach ($data['products'] as $requisition_product) {
        $to_save_stock[$requisition_product['requisition_product_id']] = $requisition_product['stock'];
        $to_save_comment[$requisition_product['requisition_product_id']] = $requisition_product['comment'];
      }

      $to_save_stock2 = array();

      // $id = I('rost.ro_id');
      $id = $data['requisition_id'];
      if(!$id){
        $id=0;
      }
      $requisition = $this->model_sale_requisition->getRequisition($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量

      if($requisition['status'] != 2) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭库存调整单')));
        return;
      }

      $requisition_products = $this->model_sale_requisition->getRequisitionProducts($id);

      foreach ($requisition_products as $requisition_p) {
        if(isset($to_save_stock[$requisition_p['id']])) {
          $to_save_stock2[$requisition_p['id']] = $to_save_stock[$requisition_p['id']];
          $to_save_comment2[$requisition_p['id']] = $to_save_comment[$requisition_p['id']];
        }
        if(isset($to_save_comment[$requisition_p['id']])) {
          $to_save_comment2[$requisition_p['id']] = $to_save_comment[$requisition_p['id']];
        }
        $num_change = $requisition_p['qty']+$to_save_stock2[$requisition_p['id']];
        if($num_change<=0){
          $error_warning = "请填写正确的调整数量";
        }
      }
       if($error_warning){
        $this->response->setOutput(json_encode(array('error'=>$error_warning)));
       }else{
        $this->model_sale_requisition->setStock($id, $to_save_stock2);
        $this->model_sale_requisition->setComment($id, $to_save_comment2);
        $this->response->setOutput(json_encode(array('success'=>'修改成功')));
       }
      
      return;
    } 
  }

  public function forceCompletePo() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/requisition');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_requisition->getPo($id);
      //判断po状态
      if($po['status'] != 3) {
        $this->response->setOutput(json_encode(array('error'=>'只能审核完成部分收货状态调拨单')));
        return;
      }

      if($po['status'] == 3) {
        //修改po单的total
        $po_products = $this->model_sale_requisition->getRequisitionProducts($id);
        $new_total = 0;
        foreach ($po_products as $po_product) {
          $new_total += (float)$po_product['unit_price']*(float)$po_product['delivered_qty'];
        }
        $this->model_sale_requisition->setPoTotal($id, $new_total);

        //修改po的status到审核完成
        $po_status = 6;
        $this->model_sale_requisition->changePoStatus($id, $po_status);

        //添加po状态修改操作记录
        $this->load->model('user/user');
        $user_info = $this->model_user_user->getUser($this->user->getId());
        $comment = '审核完成调拨单。调拨单金额改为：' . $new_total . '￥';
        $this->model_sale_requisition->addPoHistory($id, $this->user->getId(), $user_info['fullname'], $comment);  
      }

      $this->response->setOutput(json_encode(array('success'=>'修改调拨单状态成功')));
      return;
    } 
  }
  public function exportLists(){

    $this->load->model('sale/requisition');

    $data = I('get.');

    if(isset($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '0000-00-00';
    }

    if(isset($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end']." 23:59:59";
    }else{
      $filter_date_end = '9999-12-31 23:59:59';
    }

    $filter['ro.date_added'] = array('between',array($filter_date_start,$filter_date_end));

    if(!empty($data['filter_src_logcenter'])){
      $filter_src_logcenter = trim($data['filter_src_logcenter']);
      $filter['ro.src_logcenter'] = $filter_src_logcenter;
    }

    if(!empty($data['filter_des_logcenter'])){
      $filter_des_logcenter = trim($data['filter_des_logcenter']);
      $filter['ro.des_logcenter'] = $filter_des_logcenter;
    }

    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['ro.status'] = $filter_status;
      }  
    }else{
      $data['filter_status'] = '*';
    }

    $ro_list =  $this->model_sale_requisition->getAllProductList($filter);

    $status_array = getRequisitionStatus();
    foreach ($ro_list as $key => $value) {
      $save_data[] = array(
        'id'            =>  $key+1,
        'name'          =>  $value['name'],
        'option_name'   =>  $value['option_name'],
        'qty'           =>  $value['qty'],
        'price'         =>  $value['price'],
        'unit_price'    =>  $value['unit_price'],
        'deliver_time'  =>  $value['deliver_time'],
        'packing_no'    =>  $value['packing_no'],
        'date_added'    =>  $value['date_added'],
        'total'         =>  $value['qty']*$value['unit_price'],
        'vendor_name'   =>  $value['vendor_name'],
        'model'         =>  $value['model'],
        'logcenter_name'=>  $value['logcenter_name'],
        'status'        =>  $status_array[$value['status']],
        'src'           =>  $value['src'],
        'des'           =>  $value['des'],
        );
    }

    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();    
    $objProps = $objPHPExcel->getProperties();    
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");    
    $objProps->setTitle("Think-tec Contact");    
    $objProps->setSubject("Think-tec Contact Data");    
    $objProps->setDescription("Think-tec Contact Data");    
    $objProps->setKeywords("Think-tec Contact");    
    $objProps->setCategory("Think-tec");
    $objPHPExcel->setActiveSheetIndex(0);     
    $objActSheet = $objPHPExcel->getActiveSheet(); 
       
    $objActSheet->setTitle('Sheet1');
    $col_idx = 'A';
    $headers = array( '编号','商品名称','选项', '单价','数量','总价','箱入数', '创建时间', '调拨时间', '供应商', '源物流中心', '目的物流中心',     '型号', '调拨单状态');
    $row_keys = array('id','name','option_name','unit_price','qty','total','packing_no','date_added', 'deliver_time', 'vendor_name','src','des',  'model', 'status');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($save_data as $rlst) {
      $col_idx = 'A';
      foreach ($row_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    } 

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="return_main_order_'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }

  public function addProductInitiai($requisition_id){
      $this->load->model('sale/requisition');
      $this->model_sale_requisition->minusProductInitiai($requisition_id);
  }
	
	//导出模板
	public function exportTpl(){

		$this->load->library('PHPExcel/PHPExcel');
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");    
		$objProps->setTitle("Think-tec Contact");    
		$objProps->setSubject("Think-tec Contact Data");    
		$objProps->setDescription("Think-tec Contact Data");    
		$objProps->setKeywords("Think-tec Contact");    
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		   
		$objActSheet->setTitle('Sheet1');
		$col_idx = 'A';
		$headers = array( '条码','选项名','数量','目的物流中心');
		foreach ($headers as $header) {
		  $objActSheet->setCellValue($col_idx++.'1', $header);  
		}

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		
		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="requisition_logcenter_tpl'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		$objWriter->save('php://output'); 
		exit;
	}
	
	//导入
	public function import() {
		$json = array();
		if (1) {
		  if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
			// Sanitize the filename
			$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
			// Validate the filename length
			if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
			  $json['error'] = '文件名过短';
			}
			// Allowed file extension types
			$allowed = array('xls','xlsx');
			if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
			  $json['error'] = '请上传xls或者xlsx文件';
			}
			// Return any upload error
			if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
			  $json['error'] = '上传出现错误';
			}
		  } 
		}
		else {
		  $json['error'] = '上传失败';
		}

		if (!$json) {
		  $this->load->library('PHPExcel/PHPExcel');
		  $savePath = $this->request->files['file']['tmp_name'];
		  $PHPExcel = new PHPExcel();
		  $PHPReader = new PHPExcel_Reader_Excel2007();
		  if(!$PHPReader->canRead($savePath)){
			$PHPReader = new PHPExcel_Reader_Excel5();
		  }
		  $PHPExcel = $PHPReader->load($savePath);
		  $currentSheet = $PHPExcel->getSheet(0);
		  $allRow = $currentSheet->getHighestRow();
		  //获取order_product_id, express_name, express_number在excel中的index
		  $sku_idx = $option_name_idx = $qty_idx = $des_logcenter_idx = 0;
		  $tmp_idx = 'A'; //假设导入表格不会长于Z
		  $currentRow = 1;
		  while(($tmp_idx === 0 || $option_name_idx === 0 || $qty_idx === 0 || $des_logcenter_idx === 0)&&$tmp_idx<'Z') {
			switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
			  case '条码':
				$sku_idx = $tmp_idx;
				break;
			  case '选项名':
				$option_name_idx = $tmp_idx;
				break;
			  case '数量':
				$qty_idx = $tmp_idx;
				break;
			  case '目的物流中心':
				$des_logcenter_idx = $tmp_idx;
				break;
			}
			$tmp_idx++;
		  }
		  
		  if(0 === $sku_idx || 0 === $option_name_idx||0 === $qty_idx||0 === $des_logcenter_idx) {
			$json['error'] = '请检查文件第一行是否有：条码、选项名、数量、目的物流中心';
		  }
		  
		  if (!$json) {
			//默认第一行有目的物流中心
			$des_logcenter_name = (String)$currentSheet->getCell($des_logcenter_idx.'2')->getValue();
			$this->load->model('catalog/logcenter');
			$logcenter_info = $this->model_catalog_logcenter->getLogcenterByName($des_logcenter_name);
			if(!$logcenter_info) {
			  $json['error'] = '未找到供应商';
			  $this->response->addHeader('Content-Type: application/json');
			  $this->response->setOutput(json_encode($json));
			  return;
			}

			$this->load->model('catalog/product');
			$products_info = array();
			for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
			  $sku = (String)$currentSheet->getCell($sku_idx.$currentRow)->getValue();
			  $option_name = (String)$currentSheet->getCell($option_name_idx.$currentRow)->getValue();
			  $qty = (String)$currentSheet->getCell($qty_idx.$currentRow)->getValue();
			  

			  //检查sku是否存在
			  $product = $this->model_catalog_product->getProductBySku($sku);
			  // var_dump($product);
			  if(empty($product)) {
				$json['error'] = '第' . $currentRow . '行条码对应商品未找到';
			  }
			  //检查此商品是否有选项
			  if(!isset($json['error'])) {
				if(!empty($product['option'])) {
				  //如果有选项则判断当前的选项是否和sku匹配
				  if(!array_key_exists($option_name, $product['option'])) {
					$json['error'] = '第' . $currentRow . '行选项名不属于此条码商品';
				  }
				}
			  }
			  
			  if(isset($json['error'])) {
				$this->response->addHeader('Content-Type: application/json');
				$this->response->setOutput(json_encode($json));
				return;
			  }
			  
			  $product_cost = M('vendor')->where(array('vproduct_id'=>$product['product_id']))->getField('product_cost');
			  $product_data['product_id'] = $product['product_id'];
			  $product_data['qty'] = $qty;
			  $product_data['delivered_qty'] = 0;
			  $product_data['unit_price'] = $product_cost;
			  $product_data['status'] = $product['status'];
			  $product_data['name'] = $product['name'];
			  $product_data['sku'] = $product['sku'];
			  $product_data['comment'] = '';
			  $product_data['option'] = array();
			  $product_data['option']['product_option_value_id'] = $product['option'][$option_name];
			  $product_data['option']['name'] = array_key_exists($option_name, $product['option'])?$option_name:'';

			  $product_data['trim_status'] = $trim_status_map[$trim_status];
			  $product_data['comment'] = $comment;

			  $products_info[] = $product_data;
			}        

			//拼装addRo数据
			$ro_data['deliver_time'] = date('Y-m-d H:i:s', time());
			$ro_data['logcenter'] = array();
			$ro_data['logcenter']['logcenter_id'] = $logcenter_info['logcenter_id'];
			$ro_data['vendor'] = array();
			$ro_data['vendor']['user_id'] = '0';
			$ro_data['included_order_ids'] = '';
			$ro_data['products'] = $products_info;
			//调用addRo
			$this->load->model('sale/requisition');
			$requisition_id = $this->model_sale_requisition->addRequisition($ro_data, $this->user->getId());

			$this->model_sale_requisition->addRequisitionHistory($requisition_id, $this->user->getId(), $this->user->getUserName(), '导入调拨单');
		  }

		  if (!isset($json['error'])) {
			$json['success'] = sprintf('更新新建调拨单 %s条商品记录', count($ro_data['products']));
		  }
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));

	}

}